<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author LYS
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'bas:mes:team:basMesTeam:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #basMesTeamOperatorList>
        <BasicTable
          @register="registerBasMesTeamOperatorTable"
          @row-click="handleBasMesTeamOperatorRowClick"
        />
        <a-button
          class="mt-2"
          @click="handleBasMesTeamOperatorAdd"
          v-auth="'bas:mes:team:basMesTeam:edit'"
        >
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
      </template>
    </BasicForm>
    <ListSelect
      selectType="basMesRouteSelect"
      :checkbox="true"
      :params="queryParams"
      :selectList="listSelectRef"
      ref="routeSelectRef"
      @select="handSelect"
      v-show="false"
    />
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsBasMesTeamBasMesTeamForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasMesTeam, basMesTeamSave, basMesTeamForm } from '/@/api/bas/mes/team/basMesTeam';
  import { basOperatorTreeData } from '/@/api/bas/mes/operator/basOperator';
  import { officeTreeData } from '/@/api/sys/office';
  import { ListSelect } from '/@/components/ListSelect';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('bas.mes.team.basMesTeam');
  const { showMessage } = useMessage();
  const record = ref<BasMesTeam>({} as BasMesTeam);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增班组档案') : t('编辑班组档案'),
  }));

  let listSelectRef = ref([]);
  let queryParams = ref({});
  let routeSelectRef = ref<any>(null);

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('班组编码'),
      field: 'code',
      component: 'Input',
      componentProps: {
        maxlength: 100,
        allowClear: true,
      },
      required: true,
    },
    {
      label: t('班组名称'),
      field: 'name',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      required: true,
    },
    {
      label: t('所属车间'),
      field: 'officeId',
      fieldLabel: 'workShop.officeName',
      component: 'TreeSelect',
      componentProps: {
        api: officeTreeData,
        params: { isLoadUser: false, userIdPrefix: '' },
        canSelectParent: false,
        allowClear: true,
      },
      required: true,
      itemProps: { validateTrigger: 'blur' },
    },
    {
      label: t('备注'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('班组人员'),
      field: 'basMesTeamOperatorList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'basMesTeamOperatorList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerBasMesTeamOperatorTable, basMesTeamOperatorTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleBasMesTeamOperatorDelete.bind(this, record),
          },
          auth: 'bas:mes:team:basMesTeam:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setBasMesTeamOperatorTableData(_res: Recordable) {
    basMesTeamOperatorTable.setColumns([
      {
        title: t('工序编码'),
        dataIndex: 'operCode',
        width: 100,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
        fixed: 'left',
      },
      {
        title: t('工序名称'),
        dataIndex: 'basOper.name',
        width: 120,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
        fixed: 'left',
      },
      {
        title: t('操作工'),
        dataIndex: 'operator',
        width: 200,
        align: 'left',
        editRow: true,
        editable: true,
        editComponent: 'TreeSelect',
        editComponentProps: {
          api: basOperatorTreeData,
          params: { isLoadUser: true, userIdPrefix: '' },
          canSelectParent: false,
          treeCheckable: true,
          immediate: true,
        },
      },
    ]);
    basMesTeamOperatorTable.setTableData(record.value.basMesTeamOperatorList || []);
  }

  function handleBasMesTeamOperatorRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleBasMesTeamOperatorAdd() {
    routeSelectRef.value.openSelectModal();
  }

  function handleBasMesTeamOperatorDelete(record: Recordable) {
    basMesTeamOperatorTable.deleteTableDataRecord(record);
  }

  async function getBasMesTeamOperatorList() {
    let basMesTeamOperatorListValid = true;
    let basMesTeamOperatorList: Recordable[] = [];
    for (const record of basMesTeamOperatorTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        basMesTeamOperatorListValid = false;
      }
      basMesTeamOperatorList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of basMesTeamOperatorTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      basMesTeamOperatorList.push({
        ...record,
        status: '1',
      });
    }
    if (!basMesTeamOperatorListValid) {
      throw { errorFields: [{ name: ['basMesTeamOperatorList'] }] };
    }
    return basMesTeamOperatorList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await basMesTeamForm(data);
    record.value = (res.basMesTeam || {}) as BasMesTeam;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setBasMesTeamOperatorTableData(res);
    updateSchema([
      {
        field: 'code',
        componentProps: {
          disabled: !record.value.isNewRecord,
        },
      },
    ]);
    setDrawerProps({ loading: false });
  });

   // 工序选择
   function handSelect(selectData) {
    selectData.forEach((item) => {
      basMesTeamOperatorTable.insertTableDataRecord({
        id: new Date().getTime(),
        isNewRecord: true,
        editable: true,
        operCode: item.code,
        basOper: { name: item.name },
      });
    });
  }

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        code: record.value.code,
      };
      data.basMesTeamOperatorList = await getBasMesTeamOperatorList();
      // console.log('submit', params, data, record);
      const res = await basMesTeamSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
